/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Modele;

import java.util.TreeSet;

/**
 *
 * @author Gloire
 */
public class Solver {
    
    private TreeSet<String> result;
    private Dictionnaire dico;
    
    public Solver(char[][] grille){
        dico = new Dictionnaire();
        result = boggleSolver(grille);
    }
    
    public TreeSet<String> getResult(){
        return this.result;
    }
    
    public Dictionnaire getDico(){
        return this.dico;
    }
    
    public String toString(){
        String retour = "";
        for(String mot : this.result)
            retour += mot+"\n";
        return retour;
    }
    
    public TreeSet<String> boggleSolver(char[][] m) {
        if (m == null) {
            throw new NullPointerException("The matrix cannot be null");
        }
        result = new TreeSet<String>();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[0].length; j++) {
                solve(m, i, j, m[i][j] + "", result);
            }
        }
        return result;
    }

    private void solve(char[][] m, int i, int j, String prefix, TreeSet<String> validWords) {
        assert m != null;
        assert validWords != null;

        for (int i1 = Math.max(0, i - 1); i1 < Math.min(m.length, i + 2); i1++) {
            for (int j1 = Math.max(0, j - 1); j1 < Math.min(m[0].length, j + 2); j1++) {
                if (i1 != i || j1 != j) {
                    String word = prefix+ m[i1][j1];

                    if (dico.getDico().contains(word)) {
                        validWords.add(word);
                    }

                    if (dico.getDico().subSet(word, word + Character.MAX_VALUE).size() > 0) {
                        solve(m, i1, j1, word, validWords);
                    }
                }
            }
        } 
    }
    
}
